import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Modal, Form, Input, Tree, message, Popconfirm, Tag, Select } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, KeyOutlined } from '@ant-design/icons';

const { Option } = Select;

const RoleManagement = () => {
  const [roleList, setRoleList] = useState([]);
  const [permissionList, setPermissionList] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [permissionModalVisible, setPermissionModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('添加角色');
  const [form] = Form.useForm();
  const [currentId, setCurrentId] = useState(null);
  const [currentRole, setCurrentRole] = useState(null);
  const [checkedKeys, setCheckedKeys] = useState([]);

  // 获取角色列表
  const fetchRoleList = async () => {
    setLoading(true);
    try {
      // 模拟从API获取数据
      setTimeout(() => {
        const mockRoles = [
          { id: 1, name: '管理员', description: '系统管理员，拥有所有权限', status: 1, permissions: [1, 2, 3, 4, 5, 6, 7, 8, 9] },
          { id: 2, name: '普通用户', description: '普通用户，拥有基本权限', status: 1, permissions: [1, 4, 7] },
          { id: 3, name: '访客', description: '访客，只有查看权限', status: 0, permissions: [1] },
        ];
        setRoleList(mockRoles.map(item => ({ ...item, key: item.id })));
        setLoading(false);
      }, 500);
    } catch (error) {
      message.error('获取角色列表失败');
      console.error(error);
      setLoading(false);
    }
  };

  // 获取权限列表
  const fetchPermissionList = async () => {
    try {
      // 模拟从API获取数据
      setTimeout(() => {
        const mockPermissions = [
          {
            title: '仪表盘',
            key: '1',
            children: [
              { title: '查看仪表盘', key: '1-1' }
            ]
          },
          {
            title: '系统管理',
            key: '2',
            children: [
              { 
                title: '用户管理', 
                key: '2-1',
                children: [
                  { title: '查看用户', key: '2-1-1' },
                  { title: '添加用户', key: '2-1-2' },
                  { title: '编辑用户', key: '2-1-3' },
                  { title: '删除用户', key: '2-1-4' }
                ]
              },
              { 
                title: '角色管理', 
                key: '2-2',
                children: [
                  { title: '查看角色', key: '2-2-1' },
                  { title: '添加角色', key: '2-2-2' },
                  { title: '编辑角色', key: '2-2-3' },
                  { title: '删除角色', key: '2-2-4' }
                ]
              },
              { 
                title: '菜单管理', 
                key: '2-3',
                children: [
                  { title: '查看菜单', key: '2-3-1' },
                  { title: '添加菜单', key: '2-3-2' },
                  { title: '编辑菜单', key: '2-3-3' },
                  { title: '删除菜单', key: '2-3-4' }
                ]
              }
            ]
          }
        ];
        setPermissionList(mockPermissions);
      }, 300);
    } catch (error) {
      message.error('获取权限列表失败');
      console.error(error);
    }
  };

  useEffect(() => {
    fetchRoleList();
    fetchPermissionList();
  }, []);

  // 添加或更新角色
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      
      if (currentId) {
        // 模拟更新角色
        const updatedList = roleList.map(item => 
          item.id === currentId ? { ...item, ...values } : item
        );
        setRoleList(updatedList);
        message.success('更新成功');
      } else {
        // 模拟添加角色
        const newRole = {
          id: Date.now(),
          ...values,
          status: values.status || 1,
          permissions: []
        };
        setRoleList([...roleList, { ...newRole, key: newRole.id }]);
        message.success('添加成功');
      }
      setModalVisible(false);
    } catch (error) {
      console.error('提交表单失败:', error);
    }
  };

  // 删除角色
  const handleDelete = (id) => {
    // 模拟删除角色
    const updatedList = roleList.filter(item => item.id !== id);
    setRoleList(updatedList);
    message.success('删除成功');
  };

  // 打开添加角色模态框
  const showAddModal = () => {
    setModalTitle('添加角色');
    setCurrentId(null);
    form.resetFields();
    form.setFieldsValue({ status: 1 });
    setModalVisible(true);
  };

  // 打开编辑角色模态框
  const showEditModal = (record) => {
    setModalTitle('编辑角色');
    setCurrentId(record.id);
    form.setFieldsValue(record);
    setModalVisible(true);
  };

  // 打开权限设置模态框
  const showPermissionModal = (record) => {
    setCurrentRole(record);
    setCheckedKeys(record.permissions.map(String));
    setPermissionModalVisible(true);
  };

  // 保存权限设置
  const handlePermissionSubmit = () => {
    // 模拟保存权限
    const updatedList = roleList.map(item => 
      item.id === currentRole.id ? { ...item, permissions: checkedKeys.map(Number) } : item
    );
    setRoleList(updatedList);
    setPermissionModalVisible(false);
    message.success('权限设置成功');
  };

  // 表格列配置
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80
    },
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={status === 1 ? 'green' : 'red'}>
          {status === 1 ? '启用' : '禁用'}
        </Tag>
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="primary" 
            icon={<EditOutlined />} 
            size="small"
            onClick={() => showEditModal(record)}
          >
            编辑
          </Button>
          <Button 
            type="primary" 
            icon={<KeyOutlined />} 
            size="small"
            onClick={() => showPermissionModal(record)}
          >
            权限
          </Button>
          <Popconfirm
            title="确定要删除此角色吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              type="primary" 
              danger 
              icon={<DeleteOutlined />} 
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Button 
          type="primary" 
          icon={<PlusOutlined />} 
          onClick={showAddModal}
        >
          添加角色
        </Button>
      </div>
      
      <Table 
        columns={columns} 
        dataSource={roleList} 
        loading={loading}
        pagination={{ pageSize: 10 }}
        rowKey="id"
      />
      
      {/* 添加/编辑角色模态框 */}
      <Modal
        title={modalTitle}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{ status: 1 }}
        >
          <Form.Item
            name="name"
            label="角色名称"
            rules={[{ required: true, message: '请输入角色名称' }]}
          >
            <Input placeholder="请输入角色名称" />
          </Form.Item>
          
          <Form.Item
            name="description"
            label="描述"
          >
            <Input.TextArea placeholder="请输入角色描述" rows={4} />
          </Form.Item>
          
          <Form.Item
            name="status"
            label="状态"
          >
            <Select>
              <Option value={1}>启用</Option>
              <Option value={0}>禁用</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
      
      {/* 权限设置模态框 */}
      <Modal
        title={`设置权限 - ${currentRole?.name}`}
        open={permissionModalVisible}
        onOk={handlePermissionSubmit}
        onCancel={() => setPermissionModalVisible(false)}
        width={600}
      >
        <Tree
          checkable
          defaultExpandAll
          checkedKeys={checkedKeys}
          onCheck={setCheckedKeys}
          treeData={permissionList}
        />
      </Modal>
    </div>
  );
};

export default RoleManagement;